package com.nx.platform.es.biz.esspider.handler;

import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.nx.platform.es.biz.esspider.entity.Item;
import com.nx.platform.es.common.utils.MoreMaps;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 根据分割特定字符分割字段
 * <p>
 * Created by  on 2017/4/7.
 */
@HandlerDefine(HandlerType.SIMPLE)
public class SimpleSplitHandler extends AbstractSimpleHandler {

    private String field;
    private String delimiter;

    @Override
    public void init(Map<?, ?> settings) throws Exception {
        field = MoreMaps.getString(settings, "field");
        delimiter = MoreMaps.getString(settings, "separator", ",");
        Preconditions.checkArgument(!Strings.isNullOrEmpty(field), "field null or empty");
    }

    @Override
    public void handle(Map<Long, Item> items) throws Exception {
        items.values().forEach((Item item) -> {
            Map<String, Object> doc = item.getDoc();
            Object oriValue = doc.get(field);
            if (oriValue instanceof String) {
                List<String> temp = Splitter.on(delimiter).trimResults().omitEmptyStrings().splitToList(String.valueOf(oriValue));
                doc.replace(field, new ArrayList<>(temp));
            }
        });
    }

}
